package com.wy.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wy.controller.dto.OrderDTO;
import com.wy.controller.dto.OrderDetailDTO;
import com.wy.entity.Diagnosis;
import com.wy.entity.OrderDetail;
import com.wy.entity.PetAuxiliaryCheck;
import com.wy.service.*;
import com.wy.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wy.common.R;

import com.wy.entity.Order;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author 王昭贵
 * @since 2023-04-23
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderDetailService orderDetailService;

    @Resource
    private IUserService userService;

    @Resource
    private IDiagnosisService diagnosisService;

    @Resource
    private IPetService petService;

    @Resource
    private IAuxiliaryCheckService auxiliaryCheckService;

    @Resource
    private ICustomerService customerService;

    @Resource
    private IPetAuxiliaryCheckService petAuxiliaryCheckService;

    @Resource
    private IDrugService drugService;
    // 新增或者更新
    /****
     * 前台结算跳转订单详情 根据订单号获取订单详情数据
     * @param code
     * @return
     */
    @GetMapping("/getOrderDetail/{code}")
    public R<OrderDTO> getOrderDetail(@PathVariable String code) {
        OrderDTO orderDTO=new OrderDTO();
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCode,code);
        Order order = orderService.getOne(queryWrapper);
        LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OrderDetail::getOrderId,order.getId());
        List<OrderDetail> list = orderDetailService.list(queryWrapper1);
        List<OrderDetailDTO> list1 =new ArrayList<>();
        list.forEach(item->{
            OrderDetailDTO orderDetailDTO =new OrderDetailDTO();
            BeanUtil.copyProperties(item,orderDetailDTO);
            orderDetailDTO.setDrugName(drugService.getById(item.getSourceId()).getDrugName());
            orderDetailDTO.setImage(drugService.getById(item.getSourceId()).getImg());
            list1.add(orderDetailDTO);
        });
        orderDTO.setCode(order.getCode());
        BeanUtil.copyProperties(order,orderDTO);
        orderDTO.setOrderDetailDTOList(list1);
        return R.success(orderDTO);
    }
    /****
     * 主页本周收入报表
     * @return
     */
    @GetMapping("/getbeforeweekorder")
    public R getOrderList(){
        List<Order> orderList = orderService.getOrderList();
        Map<String, BigDecimal> stringBigDecimalMap = this.groupOrdersByWeekday(orderList);
        BigDecimal[] arr=new BigDecimal[7];
        int i=0;
        for (int j = 0; j < stringBigDecimalMap.size(); j++) {
            BigDecimal bigDecimal = stringBigDecimalMap.get("");
            arr[i++]=bigDecimal;
        }
        return R.success(stringBigDecimalMap);
    }
    /****
     * 删除订单
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        orderService.removeById(id);
        return R.success("");
    }
    /****
     * 用户支付订单
     * @param orderId
     * @return
     */
    @Transactional
    @GetMapping("/final")
    public R finalOrder(@RequestParam String orderId){
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getCode,orderId);
        Order order = orderService.getOne(orderLambdaQueryWrapper);
        order.setPayStatus(1);
        LambdaQueryWrapper<PetAuxiliaryCheck> petAuxiliaryCheckLambdaQueryWrapper =new LambdaQueryWrapper<>();
        petAuxiliaryCheckLambdaQueryWrapper.eq(PetAuxiliaryCheck::getOrderId,order.getId());
        List<PetAuxiliaryCheck> list = petAuxiliaryCheckService.list(petAuxiliaryCheckLambdaQueryWrapper);
        list.forEach(item->{
            item.setStatus(1);
            petAuxiliaryCheckService.updateById(item);
        });
        orderService.updateById(order);
        return R.success("");
    }
    /****
     *  后台订单管理 分页
     * @param name
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R findBackPage(@RequestParam String name,@RequestParam Integer page,
                      @RequestParam Integer pageSize) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Order::getCode,name);
        queryWrapper.orderByDesc(Order::getId);
        Page<Order> pageList = orderService.page(new Page<>(page, pageSize), queryWrapper);
        pageList.getRecords().stream().forEach(item->{
            item.setCustomerName(customerService.getById(item.getCustomerId()).getUsername());
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderDetailList.stream().forEach(orderDetail->{
                Diagnosis diagnosis = diagnosisService.getById(item.getDiagnosisId());
                String username="";
                String petName="";
                if(diagnosis!=null){
                    username= userService.getById(diagnosis.getUserId()).getUsername();
                    petName = petService.getById(diagnosis.getPetId()).getName();
                }
                if(orderDetail.getSourceType() == 0){
                    String checkName = auxiliaryCheckService.getById(orderDetail.getSourceId()).getCheckName();
                    orderDetail.setCheckName(checkName);
                }else {
                    String durgName= drugService.getById(orderDetail.getSourceId()).getDrugName();
                    orderDetail.setCheckName(durgName);
                }
                orderDetail.setUserName(username);
                orderDetail.setPetName(petName);
            });
            item.setOrderDetailList(orderDetailList);
        });
        return R.success(pageList);
    }

    /****
     * 前台 用户获取订单详情列表分页
     * @param customerId
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/frontpage")
    public R findFrontPage(@RequestParam int customerId,@RequestParam Integer page,
                                @RequestParam Integer pageSize) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCustomerId,customerId);
        queryWrapper.orderByDesc(Order::getId);
        Page<Order> pageList = orderService.page(new Page<>(page, pageSize), queryWrapper);
        pageList.getRecords().stream().forEach(item->{
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(orderDetailLambdaQueryWrapper);
            orderDetailList.stream().forEach(orderDetail->{
                if(orderDetail.getSourceType() == 0){
                    String checkName = auxiliaryCheckService.getById(orderDetail.getSourceId()).getCheckName();
                    orderDetail.setCheckName(checkName);
                }else {
                    String durgName= drugService.getById(orderDetail.getSourceId()).getDrugName();
                    orderDetail.setCheckName(durgName);
                }
                Diagnosis diagnosis = diagnosisService.getById(item.getDiagnosisId());
                if(diagnosis!=null){
                    String username = userService.getById(diagnosis.getUserId()).getNickname();
                    String petName = petService.getById(diagnosis.getPetId()).getName();
                    orderDetail.setUserName(username);
                    orderDetail.setPetName(petName);
                }

            });
            item.setOrderDetailList(orderDetailList);
        });
        return R.success(pageList);
        
    }
    public Map<String, BigDecimal> groupOrdersByWeekday(List<Order> orders) {
        // 定义一个 Map 用于存储按照星期分组后的订单数据
        Map<String, BigDecimal> result = new LinkedHashMap<>(); // 使用 LinkedHashMap，确保顺序正确

        // 初始化 Map，将所有日期的值设置为 0
        List<String> weekdays = Arrays.asList("周一", "周二", "周三", "周四", "周五", "周六", "周日");
        for (String weekday : weekdays) {
            result.put(weekday, BigDecimal.ZERO);
        }

        // 遍历订单数据，将其按照星期分组
        for (Order order : orders) {
            Date orderTime = Date.from((order.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()));
            BigDecimal orderAmount = order.getPayPrice();
            String weekday = DateUtils.getWeekday(orderTime); // 获取星期几，例如"周一"

            // 将订单金额累加到对应的星期中
            BigDecimal totalAmount = result.get(weekday);
            totalAmount = totalAmount.add(orderAmount);
            result.put(weekday, totalAmount);
        }

        return result;
    }

}

